<script>
  import mixins from './mixins'
  import { isObject } from '../../utils/validate'
  import common from '../../utils/common'
  import moment from 'moment'
  import asthmaUtils from '../../views/reception/components/asthma/utils.js'

  export default {
    name: 'EMRCell',
    props: {
      data: Object,
      title: String,
      subtitle: String,
      disabled: Boolean,
      docType: [Number, String],
    },
    data() {
      return {
        form: {},
        // 病历类型
      }
    },
    computed: {
      isDisabled() {
        return this.disabled
      },
      birthdayWithYear() {
        // console.log('this.recordDate =' + this.recordDate())
        const recordDate = this.recordDate()
        if (recordDate) {
          return parseInt(recordDate.split('-')[0])
        }
        return null
      },
      birthdayWithmonth() {
        const recordDate = this.recordDate()
        if (recordDate) {
          return parseInt(this.recordDate.split('-')[1])
        }
        return null
      },
    },
    watch: {
      data() {
        this.clear()
      },
      form: {
        deep: true,
        handler() {
          // 这里告诉外部 内部有值改变了
          this.$emit('change')
        },
      },
    },
    inject: [
      'asthmaBusDict',
      'asthmaBusAddBus',
      'asthmaBusUpdateBus',
      'busAllEmit',
      'recordDate',
    ],
    methods: {
      splitCondition(c, name) {
        // 'effectValue'
        if (!c || !name) return false
        const condition = c.split(',')
        if (Array.isArray(condition) && condition.length > 0) {
          const keyValue = condition.filter((item) => {
            return item.includes(name)
          })
          const key =
            keyValue.length > 0 && keyValue[0] && keyValue[0].split('=')
          if (key) return key
          return false
        }
        return false
      },
      diffTime(year, month) {
        if (!year && !month) return null
        let time = this.recordDate()
        if (year) time = moment(time).subtract(year, 'year')
        if (month) time = moment(time).subtract(month, 'month')
        time = moment(time).format('YYYY-MM-DD')
        return [parseInt(time.split('-')[0]), parseInt(time.split('-')[1])]
      },
      showTips(title) {
        console.log('methods =' + title)
        this.$emit('showTips', title)
      },
      // 清理缓存
      clear() {
        this.form = {}
      },
      getData() {
        return this.form
      },
      getImageRef() {
        return this.$refs['imgFileUploadRef']
      },
      // 已转换
      $_span(title) {
        if (title) {
          return <span>{title}</span>
        }
        return null
      },
      // 根据单元格类型渲染对应的组件
      $_returnCom(cell, index, isC) {
        // 解构单元格属性
        const { t, an, b } = cell  // t: 单元格类型, an: 属性名, b: 配置对象
        const { v, w, bt, at, c } = b // bt: 前缀文本, at: 后缀文本, v: 值, c: 条件, w: 宽度
        let condition = []  // 条件数组
        if (v) {
          // 保留v的处理逻辑
        }
        if (c) {
          condition = c.split(',')  // 将条件字符串分割为数组
        }
        let children = null
        // 处理子单元格 - 排除不需要递归处理的类型(r2/c2/c3)
        if (cell.children && t !== 'r2' && t !== 'c2' && t !== 'c3') {
          children = cell.children.map((item) => {
            if (item === null) {
              console.log('cell ' + JSON.stringify(cell))
            }
            if (cell.disabled) item['disabled'] = true  // 继承父级禁用状态
            return this.$_returnCom(item)  // 递归处理子单元格
          })
        }
        const btc = this.$_span(bt)  // 渲染前缀文本
        const atc = this.$_span(at)  // 渲染后缀文本
        if (t === 'r1') {
          // 单选按钮组类型
          const key = this.splitCondition(cell.b.c, 'onlyValue')
          if (key) {
            const activeOn = (notClearAttr) => {
              if (notClearAttr === cell.an) return
              this.form[cell.an] = []  // 清除非当前属性的值
            }
            const activeEmit = (notClearAttr) => {
              this.busAllEmit(key, notClearAttr)  // 触发事件总线
            }
            this.asthmaBusAddBus(cell.an, activeOn, key)  // 注册事件监听
            return mixins.$_r1(
              cell,
              index,
              this.form,
              isC,
              children,
              activeEmit,
              this.recordDate()
            )
          }
          return mixins.$_r1(
            cell,
            index,
            this.form,
            isC,
            children,
            null,
            this.recordDate()
          )
        } else if (t === 'c1') {
          // 复选框组类型
          const key = this.splitCondition(cell.b.c, 'syncValue')
          if (key) {
            const activeOn = (vals) => {
              // 处理属性间的同步逻辑
              const { attr, value } = vals
              if (attr === 'attr11') {
                if (value.includes('反复咳嗽') && value.includes('伴喘息')) {
                  this.form['attr1'] = ['咳嗽', '伴喘息']
                } else if (value.includes('反复咳嗽')) {
                  this.form['attr1'] = ['咳嗽']
                } else if (value.includes('伴喘息')) {
                  this.form['attr1'] = ['伴喘息']
                } else {
                  this.form['attr1'] = []
                }
              } else if (attr === 'attr1') {
                if (value.includes('咳嗽') && value.includes('伴喘息')) {
                  this.form['attr11'] = ['反复咳嗽', '伴喘息']
                } else if (value.includes('咳嗽')) {
                  this.form['attr11'] = ['反复咳嗽']
                } else if (value.includes('伴喘息')) {
                  this.form['attr11'] = ['伴喘息']
                } else {
                  this.form['attr11'] = []
                }
              }
            }
            const activeEmit = (notClearAttr) => {
              this.busAllEmit(key, notClearAttr)  // 触发事件总线
            }
            this.asthmaBusAddBus(cell.an, activeOn, key)  // 注册事件监听
            return mixins.$_c1(
              cell,
              index,
              this.form,
              isC,
              children,
              activeEmit
            )
          }
          return mixins.$_c1(cell, index, this.form, isC, children)
        } else if (t === 'i1') {
          // 输入框类型
          const key = this.splitCondition(cell.b.c, 'effectValue')
          const activeOn = (value) => {
            // 处理时间差值计算
            const { attr2, attr3 } = value
            const tmp = this.diffTime(attr2, attr3)
            if (tmp) {
              this.form['attr9'] = tmp[0]  // 年差值
              this.form['attr10'] = tmp[1]  // 月差值
            }
          }
          this.asthmaBusAddBus(cell.an, activeOn, key)  // 注册事件监听
          return mixins.$_i1(cell, index, this.form, isC)
        } else if (t === 'i2') {
          // 多行文本输入框类型
          const st = { width: w ? w + 'px' : '100%' }  // 设置宽度样式
          return (
            <span class={condition.includes('nib') ? 'block' : 'inline-block'}>
              {btc}
              <el-input
                size="large"
                type="textarea"
                placeholder="补充内容,限制100个字符以内 "
                maxlength="100"
                v-model={this.form[an]}
                style={st}
              ></el-input>
              {atc}
            </span>
          )
        } else if (t === 's1') {
          // 选择器类型
          const key = this.splitCondition(cell.b.c, 'effectValue')
          if (key) {
            const activeEmit = (value) => {
              // 特殊处理attr2和attr3的双向绑定
              if (cell.an === 'attr2' || cell.an === 'attr3') {
                this.busAllEmit(
                  key,
                  JSON.parse(
                    JSON.stringify({
                      attr2: this.form['attr2'],
                      attr3: this.form['attr3'],
                    })
                  )
                )
              } else {
                this.busAllEmit(key, value)  // 触发事件总线
              }
            }
            return mixins.$_s1(cell, index, this.form, isC, activeEmit)
          }
          return mixins.$_s1(cell, index, this.form, isC)
        } else if (t === 'l1') {
          // 空div占位类型
          return <div></div>
        } else if (t === 'img1') {
          // 图片上传类型
          return mixins.$_img1(cell, index, this.form, isC)
        } else if (t === 'medicineList') {
          // 药品列表类型
          return mixins.$_medicineList(cell, index, this.form, isC)
        } else if (t === 'r2') {
          // 特殊单选按钮组类型(带子项)
          return mixins.$_r2(
            cell,
            index,
            this.form,
            isC,
            children,
            this.$_returnCom
          )
        } else if (t === 'c2') {
          // 特殊复选框组类型(带子项)
          return mixins.$_c2(
            cell,
            index,
            this.form,
            isC,
            children,
            this.$_returnCom
          )
        } else if (t === 't1') {
          // 纯文本类型
          return mixins.$_t1(cell)
        } else if (t === 't2') {
          // 带点击事件的文本类型
          const self = this
          const clickEvent = function (title) {
            // 根据文本内容触发不同事件
            if (title.includes('控制水平')) {
              self.$emit('clickEvent', { name: 'clickControl' })
            } else if (
              title.includes('急性喘息发作') ||
              title.includes('支气管哮喘急性发作')
            ) {
              self.$emit('clickEvent', { name: 'clickacute' })
            }
          }
          return mixins.$_t2(cell, index, this.form, clickEvent)
        } else if (t === 'c3') {
          // 特殊复选框类型(无子项)
          return mixins.$_c3(cell, index, this.form)
        } else if (t === 'timeSelect') {
          // 时间选择器类型
          return mixins.$_timeSelect(cell, index, this.form)
        }
      },
      async clearSeciton() {
        await common.syncAlert(
          // eslint-disable-next-line max-len
          '点击"确定"按钮会清理当前段落所有数据，<span style="color: red">如需取消单项勾选，再次点击选中的勾选即可取消。<span>',
          true
        )
        this.clearSecitonIP(this.data, this.form)
      },
      /**
       * 清除每一段的用户首选的值
       * 1. 循环每一项，子模块也需要清理
       * 2. 清理ip中的值。d字段有默认值赋值
       * 3. 清理from中的值
       */
      clearSecitonIP(data, form) {
        if (data && Array.isArray(data)) {
          data.map((cell) => {
            if (!cell) return
            if (cell.t === 'c1' || cell.t === 'c2') {
              form[cell.an] = cell.b.d ? [cell.b.d] : []
              cell.b.ip = null
            } else {
              console.log('cell.an =' + cell.an)
              form[cell.an] = cell.b.d ? cell.b.d : ''
              cell.b.ip = null
            }
            if (Array.isArray(cell.children) && cell.children.length > 0) {
              console.log('cell.children =' + cell.children.length)
              cell.children.map((item) => {
                console.log('item =' + JSON.stringify(item))
                this.clearSecitonIP(item, form)
              })
            }
          })
        } else if (isObject(data)) {
          if (!data || !data.an) return
          if (data.t === 'c1' || data.t === 'c2') {
            form[data.an] = data.b.d ? data.b.d : []
            data.b.ip = null
          } else {
            form[data.an] = data.b.d ? data.b.d : ''
            data.b.ip = null
          }
        }
      },
    },
    render() {
      console.log('render')
      const configs = this.data
      const formItem = configs.map((config, index) => {
        if (this.disabled) config['disabled'] = this.disabled
        // if (Array.isArray(config.children) && config.children.length) {
        // }
        return this.$_returnCom(config, index, false)
      })
      // 渲染整个cell
      const isTitleTips =
        asthmaUtils.isAsthmaDocType(this.docType) &&
        this.subtitle === null &&
        this.title !== '体格检查' &&
        this.title !== '辅助检查' &&
        this.title !== '个人史' &&
        this.title !== '中医辨证'
      const isSubtitleTips =
        asthmaUtils.isAsthmaDocType(this.docType) &&
        this.subtitle !== null &&
        this.subtitle !== '体格检查' &&
        this.subtitle !== '个人史' &&
        this.title !== '中医辨证'
      // 兼容体格检查未有 兼容中医诊断有弹窗的异常
      const isNotShowBtn =
        (asthmaUtils.isAsthmaDocType(this.docType) &&
          this.title === '现病史' &&
          this.subtitle !== null) ||
        this.title === null ||
        this.title === undefined

      const html = (
        <div class="content-wrapper">
          <h3>
            {this.title}
            {isTitleTips ? (
              <div>
                <svg-icon
                  style="margin-left: 5px"
                  icon-class="information"
                  onClick={() => this.showTips(this.title)}
                ></svg-icon>
                <el-button
                  disabled={this.disabled}
                  style="margin-left: 5px"
                  size="small"
                  type="danger"
                  onClick={() => this.clearSeciton()}
                >
                  重置内容
                </el-button>
              </div>
            ) : isNotShowBtn ? null : (
              <el-button
                disabled={this.disabled}
                style="margin-left: 5px"
                size="small"
                type="danger"
                onClick={() => this.clearSeciton()}
              >
                重置内容
              </el-button>
            )}
          </h3>
          {this.subtitle ? (
            <h3>
              {this.subtitle}
              {isSubtitleTips ? (
                <div>
                  <svg-icon
                    style="margin-left: 5px"
                    icon-class="information"
                    onClick={() => this.showTips(this.subtitle)}
                  ></svg-icon>
                  <el-button
                    disabled={this.disabled}
                    style="margin-left: 5px"
                    size="small"
                    type="danger"
                    onClick={() => this.clearSeciton()}
                  >
                    重置内容
                  </el-button>
                </div>
              ) : null}
            </h3>
          ) : (
            ''
          )}
          {formItem}
        </div>
      )
      return html
    },
  }
</script>
<style lang="scss">
  .content-wrapper {
    font-size: 18px !important;
    line-height: 18px;
    padding: 12px;
    margin: 0 0 12px 0;

    h3 {
      margin: 0;
      line-height: 2;
      font-size: 18px;
      margin-right: 12px;
      display: flex;
      align-items: center;
    }

    h3:nth-child(2) {
      font-size: 15px;
    }

    .t2-tips-class {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.65);
    }

    .image1 {
      display: flex;
      align-items: center;
    }

    .select1 {
      .el-input__wrapper {
        border-radius: 0;
        border: 0;
        padding-left: 0;
        padding-right: 0;
        box-shadow: none !important;
        border-bottom: 1px solid #d9d9d9;
        vertical-align: middle;
        padding-left: 10px;
        padding-right: 10px;
      }
    }

    .select2 {
      .el-input__wrapper {
        border-radius: 0;
        border: 0;

        box-shadow: none !important;
        border-bottom: 1px solid #d9d9d9;
        vertical-align: middle;
      }
    }

    // 取消disabled时的变色
    .el-input.is-disabled .el-input__wrapper,
    .el-checkbox__input.is-disabled .el-checkbox__inner,
    .el-radio__input.is-disabled .el-radio__inner {
      background-color: initial;
    }

    .disabledClass {
      background: #eee;
      padding: 12px;
    }

    .input1 {
      .is-disabled {
        .el-input__wrapper {
          // background-color: red;
          box-shadow: none !important;
          border-bottom: 1px solid #d9d9d9 !important;
        }
      }

      .el-input__wrapper {
        border-radius: 0;
        border: 0;
        padding-left: 1px;
        padding-right: 1px;
        height: 25px;
        line-height: 25px;
        box-shadow: none !important;
        border-bottom: 1px solid #d9d9d9;
        vertical-align: middle;
        font-size: 18px !important;
        font-weight: 400;
        // 产品要求居中显示
        text-align: center;
      }

      .el-input__wrapper:active,
      .el-input__wrapper:hover {
        box-shadow: none !important;
        border-bottom: 1px solid #409eff;
      }
    }

    .el-checkbox {
      margin-right: 5px;
      color: #303133 !important;

      .el-checkbox__inner {
        width: 16px;
        height: 16px;
        margin-bottom: 3px;
      }

      .el-checkbox__label {
        font-size: 18px !important;
        font-weight: 400;
        padding-left: 5px;
      }
    }

    .inline-block {
      line-height: 0;
    }

    .block {
      margin-top: 10px;
      display: flex;
      //align-items: flex-start;
      .el-checkbox {
        white-space: normal; word-wrap: break-word; min-height: auto; height: auto; display: flex; align-items: flex-start;
      }
      .normal-content {
        white-space: normal; word-wrap: break-word; min-height: auto; height: auto; display: flex; align-items: flex-start;
      }
    }

    .el-checkbox-group {
      display: inline-block;
      margin: 0 3px;
    }

    .el-radio-group {
      margin-left: 5px;

      .radio_tip {
        font-size: 17.5px !important;
        // font-weight: 350;
        color: #303133;
      }
    }

    .el-radio {
      margin-right: 5px;
      color: #303133 !important;

      .el-radio__inner {
        width: 16px;
        height: 16px;
        margin-bottom: 3px;
      }

      .el-radio__label {
        padding-left: 3px;
        font-size: 18px !important;
        font-weight: 400;
      }
    }
  }
</style>
